window.http = window.h = window.http||{};

(function () {

    var loadingView = null;
    function loading() {
        loadingView = document.createElement("img");
        loadingView.src = "http://liuyujing.com/happiness_order/resource/images/loading.gif";
        loadingView.width = 100;
        loadingView.style.cssText = "position:absolute;left:50%;top:50%;margin:-50px 0 0 -50px;";
        document.body.appendChild(loadingView);
    }
    function removeLoading() {
        if (loadingView) {
            document.body.removeChild(loadingView);
            loadingView = null;
        }
    }

    //网络请求相关
    function Ajax() {
        function post(url,info,callback) {

            loading();

            console.log("是否存在password：",info.hasOwnProperty("password"));

            //是不是拥有某个属性
            if (info.hasOwnProperty("password")) {
                //加密
                var code = "liuyujing";
                var first = encode.sha1.sha1(info.password+code);
                info.password = encode.md5.md5(first+code);
                console.log(info.password);
            }

            //兼容IE
            window.XMLHttpRequest = XMLHttpRequest||ActiveXObject;
            var req = new XMLHttpRequest();
            req.open("POST",url);
            req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            var token = localStorage.getItem("token");
            if (token) {
                req.setRequestHeader("token",token);
            }
            //设置超时时间
            req.timeout = 1*60*1000;
            //发送状态改变的监听函数
            req.onreadystatechange = function () {
                console.log(this.readyState);
                //readyState的值是4 就是接收到数据的状态
                /*
                * 1 准备发送数据
                * 2 发送数据
                * 3 服务端接收到数据
                * 4 服务端返回数据 接收到数据
                * */
                if (this.readyState === 4){
                    removeLoading();
                    if (this.responseText){
                        callback(JSON.parse(this.responseText));
                    } else {
                        callback({error:"未接收到数据"})
                    }
                }
            }

            req.send(encodeObjToUrl(info));
        }

        function encodeObjToUrl(info) {
            var temp = [];

            // if (info.password.length<6) {
            //     alert("密码不能少于6位")
            // } else {
                for (var key in info){
            //         if (info[key]) {
                        var res = key+"="+info[key];
                        temp.push(res);
                //     } else {
                //         alert("请输入"+key);
                //     }
                //
                // }
            }

            return temp.join("&");
        }

        //随机代码
        function randCode(bit) {
            var result = "";
            for (var i=0;i<bit;i++) {
                result+=parseInt(Math.random()*10);
            }
            return result;
        }

        function get(url,callback) {
            window.XMLHttpRequest = XMLHttpRequest||ActiveXObject;
            var req = new XMLHttpRequest();
            req.open("GET",url);
            req.onload = function () {
                if (this.response) {
                    callback(JSON.parse(this.response));
                } else {
                    callback({error:"未接收到数据"})
                }
            };
            req.send()
        }

        return{
            post:post,
            get:get
        }
    }

    //图片处理
    function ImageTool() {
        function dealImage(path, config, callback){

            var img = new Image();
            img.src = path;
            img.onload = function(){
                var that = this;
                // 默认按比例压缩
                var w = that.width,
                    h = that.height,
                    scale = w / h;
                w = config.width || w;
                h = config.height || (w / scale);
                var quality = 0.3;  // 默认图片质量为0.7
                //生成canvas
                var canvas = document.createElement('canvas');
                var ctx = canvas.getContext('2d');
                // 创建属性节点
                var anw = document.createAttribute("width");
                anw.nodeValue = w;
                var anh = document.createAttribute("height");
                anh.nodeValue = h;
                canvas.setAttributeNode(anw);
                canvas.setAttributeNode(anh);
                ctx.drawImage(that, 0, 0, w, h);
                // 图像质量
                if(config.quality && config.quality <= 1 && config.quality > 0){
                    quality = config.quality;
                }
                // quality值越小，所绘制出的图像越模糊
                var base64 = canvas.toDataURL('image/jpeg', quality );
                // 回调函数返回base64的值
                callback(base64);
            }
        }

        //上传图片
        function uploadImage(element,callback) {
            element.addEventListener("change",function (event) {
                //阻止事件冒泡行为
                event.stopPropagation();
                console.log(this.files);
                //    this.files -> 是一个伪数组 里面存放的是File类型的文件
                //    把File类型 -> URL类型

                var file = this.files[0];
                if (file.type.indexOf("image")===-1){
                    return;
                }

                //    文件读取
                var reader = new FileReader();
                reader.onload = function () {
                    //result是读取完成之后的结果
                    console.log(this.result);
                    //把转换完成的结果 发送给 传入回调函数的地方
                    dealImage(this.result,{width:200,quality:0.8},function (url) {
                        callback(url);
                    });
                };
                //读取file文件 为URL
                //异步读取
                reader.readAsDataURL(this.files[0]);

            });
        }

        return{
            //压缩图片
            dealImage:dealImage,
            uploadImage:uploadImage
        }

    }

    window.h.Ajax = Ajax();
    window.h.ImageTool = ImageTool();

    window.http = window.h;

})();